Lesson 8 - Functions

Functions use indentation, like while loops and if statements, to show what code belongs within the function. When creating a function you need -

  1. A name for the function
  2. Parameters (the values to pass through) (optional)
  3. A return value (optional)
  4. Statements to run within the function

Functions must be defined using the keyword def and a name. If no parameters are specified then you must put empty brackets otherwise you can add parameters. Finally you must add a colon. Python uses circle brackets to help identify that function is in fact a function.


def simpleFunction():
	print "hello world"
	
simpleFunction()
simpleFunction()

Python has some built in functions which can be useful when programming. You will of come across some already

You can read up more on the built in functions by reading the python documentation.

You can specify the number of parameters used by the function in the definition. Functions in python are very powerful and they will be revisited later.


def sayHello(name):
	print "hello", name
sayHello("bob") # hello bob
sayHello("fred") # hello fred
  

Finally return values can occur at any part of the function. It is assumed that there is always a return value even if on is not inserted. If no value is to be returned then you simply just write the return keyword. Any value after the return keyword is returned. This can be an expression, a value or a variable. The code below is an adaptation of the secret number guessing game. The only difference is that the value test is now done in a function. You can download this here.


import random

def testGuess(guess, secret):
    if guess > secret and diff <= 20:
            print "guess is too big"
            return False
    elif guess < secret and diff <=20:
            print "guess is too small"
            return False
    elif guess == secret:
            print "Well done you guessed correctly!"
            return True
    else:
      print "Your nowhere near!"
      return False

gameWon = False
secret = random.randrange(1,100)
lives = 5
# keep going while the game has not been won
while not gameWon and lives >0:
    guess = input("Enter a number ")
    # see if they were close or not!
    diff = guess - secret
    # diff could be negative!
    if diff < 0:
        diff = diff * -1
    gameWon = testGuess(guess, secret)
   
    lives = lives -1
    print "you have ", str(lives), " left"

# has the game been won?
if(not gameWon):
    print "You have lost. Bow your head in shame! The number was ", secret